home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C22 / Persist1.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-25  |  1.7 KB  |  75 lines

  1. //: C22:Persist1.cpp
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. // Simple persistence with MI
  7. #include "../require.h"
  8. #include <iostream>
  9. #include <fstream>
  10. using namespace std;
  11.  
  12. class Persistent {
  13.   int objSize; // Size of stored object
  14. public:
  15.   Persistent(int sz) : objSize(sz) {}
  16.   void write(ostream& out) const {
  17.     out.write((char*)this, objSize);
  18.   }
  19.   void read(istream& in) {
  20.     in.read((char*)this, objSize);
  21.   }
  22. };
  23.  
  24. class Data {
  25.   float f[3];
  26. public:
  27.   Data(float f0 = 0.0, float f1 = 0.0,
  28.     float f2 = 0.0) {
  29.     f[0] = f0;
  30.     f[1] = f1;
  31.     f[2] = f2;
  32.   }
  33.   void print(const char* msg = "") const {
  34.     if(*msg) cout << msg << "   ";
  35.     for(int i = 0; i < 3; i++)
  36.       cout << "f[" << i << "] = "
  37.            << f[i] << endl;
  38.   }
  39. };
  40.  
  41. class WData1 : public Persistent, public Data {
  42. public:
  43.   WData1(float f0 = 0.0, float f1 = 0.0,
  44.     float f2 = 0.0) : Data(f0, f1, f2),
  45.     Persistent(sizeof(WData1)) {}
  46. };
  47.  
  48. class WData2 : public Data, public Persistent {
  49. public:
  50.   WData2(float f0 = 0.0, float f1 = 0.0,
  51.     float f2 = 0.0) : Data(f0, f1, f2),
  52.     Persistent(sizeof(WData2)) {}
  53. };
  54.  
  55. int main() {
  56.   {
  57.     ofstream f1("f1.dat"), f2("f2.dat");
  58.     assure(f1, "f1.dat"); assure(f2, "f2.dat");
  59.     WData1 d1(1.1, 2.2, 3.3);
  60.     WData2 d2(4.4, 5.5, 6.6);
  61.     d1.print("d1 before storage");
  62.     d2.print("d2 before storage");
  63.     d1.write(f1);
  64.     d2.write(f2);
  65.   } // Closes files
  66.   ifstream f1("f1.dat"), f2("f2.dat");
  67.   assure(f1, "f1.dat"); assure(f2, "f2.dat");
  68.   WData1 d1;
  69.   WData2 d2;
  70.   d1.read(f1);
  71.   d2.read(f2);
  72.   d1.print("d1 after storage");
  73.   d2.print("d2 after storage");
  74. } ///:~
  75.